package com.snork.tribanspeedo;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.location.GpsStatus;

public class Speedo extends Activity implements GpsStatus.Listener {
	
	public static final String PREFS_NAME = "SpeedaData";

	protected static final int LENGTH_LONG = 0;
	protected static final int GPS_MIIN_ACC = 15;
	
	private TextView vDist, vSpeed, vOdo, vStatus;
	private Typeface mainFont;
	private LocationManager mLocationManager;
	private GpsStatus mStatus;	
	private Geocoder geocoder;
	private List<Address> addresses;
		
//	private LocationProvider mProvider;
	private Globals globalVars; 
	private SharedPreferences settings; 	
	private SharedPreferences.Editor editor;	
    private Button buttonResetODO;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_speedo);

		globalVars = Globals.getInstance();
		
	    // Restore preferences
	    settings = getSharedPreferences(PREFS_NAME, 0);
	    long odo = settings.getLong("odo", 0);	
		
		//Setup Display Areas
	    mainFont = Typeface.createFromAsset(getAssets(), "fonts/DigitalDream.ttf");
	    vDist = (TextView)findViewById(R.id.Distance);
	    vSpeed = (TextView)findViewById(R.id.Speed);	    
	    vStatus = (TextView)findViewById(R.id.Status);	    
	    vOdo = (TextView)findViewById(R.id.Odo);	    
	    vDist.setTypeface(mainFont);
	    vSpeed.setTypeface(mainFont);	
	    vStatus.setTypeface(mainFont);	    
	    vOdo.setTypeface(mainFont);	    
	    vSpeed.setTextSize(30);
	    vSpeed.setPadding(25, 0, 0, 0);

	    //Set initial Displays
    	vSpeed.setText("Waiting for GPS Fix");
        vDist.setText("Distance: " + String.format("%.2f", globalVars.getTotalDist()) + " Miles");
        vOdo.setText("Total Dist: " + Long.toString(odo));
        vStatus.setText("Message...");

    	//Setup Location
	    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
	    mLocationManager.getProvider(LocationManager.GPS_PROVIDER);
        mLocationManager.addGpsStatusListener(this);

	    buttonResetODO = (Button) findViewById(R.id.resetOdo);
        buttonResetODO.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        		editor = settings.edit();
        		editor.putLong("odo", 0);
        		editor.commit();
                vOdo.setText("Total Dist: " + 0);   
                globalVars.setTotalDist(0);
                             
            }
        });
	
    };	   
	    
    //GPS Setup
    public void onGpsStatusChanged(int event) {
        mStatus = mLocationManager.getGpsStatus(mStatus);
        switch (event) {
            case GpsStatus.GPS_EVENT_STARTED:
                // Do Something with mStatus info
                break;

            case GpsStatus.GPS_EVENT_STOPPED:
                // Do Something with mStatus info
                break;

            case GpsStatus.GPS_EVENT_FIRST_FIX:
                // Do Something with mStatus info
            	vSpeed.setText("GPS Fix Found");
          	
                break;

            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                // Do Something with mStatus info
                break;
        }

    }        
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_speedo, menu);
		return true;
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		
		mLocationManager.removeUpdates(listener);
		editor = settings.edit();
		editor.putLong("odo", (long)globalVars.getTotalDist());
		editor.commit();
	}
	
	@Override
	protected void onStart() {
		super.onStart();

		geocoder = new Geocoder(this, Locale.getDefault());
		
	    // This verification should be done during onStart() because the system calls
	    // this method when the user returns to the activity, which ensures the desired
	    // location provider is enabled each time) the activity resumes from the stopped state.
	    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	    final boolean gpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

	    if (!gpsEnabled) {
	        // Build an alert dialog here that requests that the user enable
	        // the location services, then when the user clicks the "OK" button,
	        vDist.setText("GPS Not Enabled");
	    }
	    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
	            1000,          // 1-second interval.
	            1,             // 1 meters.
	            listener);
	    
	}	    

	private final LocationListener listener = new LocationListener() {
		
		double currLat, currLong;

	    @Override
	    public void onLocationChanged(Location location) {
	        // A new location update is received.  Do something useful with it.  In this case,
	        // we're sending the update to a handler which then updates the UI with the new
	        // location.

	    	float[] curDist = new float[1];
	    	float accuracy = 0;
	    	
	    	currLat = location.getLatitude();
	    	currLong = location.getLongitude();
	    	
	    	accuracy = location.getAccuracy();

//	    	if (accuracy < GPS_MIIN_ACC) {	    	
	
	    			vStatus.setText("Location accurate to " + Float.toString(accuracy) + "m");
	    	
	    			if (globalVars.getLat() != 0 )
	    			{
	    				Location.distanceBetween(globalVars.getLat(), globalVars.getLong(), currLat, currLong, curDist);
	    				globalVars.setTotalDist(curDist[0] * 0.000621371192);
	    			}
	    			
	    			//	Save the new values
	    			globalVars.setCoords(currLat, currLong);
		
			
	    			//Convert speed from m/s to mph
	    			vSpeed.setText(String.format("%.2f", location.getSpeed() * 2.2369362920544) + " MPH");
	    			vDist.setText("Distance: " + String.format("%.2f", globalVars.getTotalDist()) + " Miles");

	    			//Get address
	    			try {
	    				//Check the service is available first
	    				//vStatus.setText(Boolean.toString(Geocoder.isPresent()));
						addresses = geocoder.getFromLocation(currLat, currLong, 1);
						vStatus.setText(addresses.get(0).getPostalCode());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	    			
	    			
//	    	}
//	    	else
//	    	{
//	    		vStatus.setText("Location NOT accurate to " + Float.toString(accuracy) + "m");
//	    	}
	    }
	    
		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub

    }

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub
			
		}
	};	


	
}
